package srzy.module

import srzy.dao.DBUtil
import srzy.common.Logging
import net.sf.jsqlparser.parser.CCJSqlParserManager
import java.io.StringReader
import net.sf.jsqlparser.statement.update.Update

object RefreshSM extends Logging {

  val smVersion = srzy.common.Config.getValue("root", "config", "Version") match {
    case "ALL" => "ALL"
    case "HN" => "HN"
    case _ => "HN"
  }
  val smName = srzy.common.Config.getValue("root", "config", "SMName")
  val dbUtil = DBUtil("SMOracleSource")
  val refreshTableMap = dbUtil.getRefreshControl.toMap
  val parserManager = new CCJSqlParserManager()

  logger.debug("refreshTableMap:" + refreshTableMap)

  def refresh(l: List[String] = List.empty[String]) = {
    if (smVersion == "HN")
      hnSMRefresh(l)
  }

  private def getRefreshFlag =
    dbUtil.executeLine("SELECT REFRESH_FLAG FROM SM_PARAMS_REFRESH_CONTROL WHERE SM_SERV = '" + smName + "'")

  private def hnSMRefresh(l: List[String]) = {
    val ll = l.map(x => parserManager.parse(new StringReader(x)) match {
      case s: Update => Some(s.getTable().getName())
      case _ => logger.error("sql is not update clouse : " + x); None
    }).map(e => e match {
      case Some(v) =>
        logger.debug("refresh Table : " + v)
        refreshTableMap.get(v.toUpperCase())
      case None => None
    })
    val refreshList = if (ll.contains(None)) {
      List("1")
    } else {
      ll.filter(_ != None).map(_.get)
    }
    refreshList.foreach(refreshTable(_))
    logger.debug("refresh data over")
  }

  def refreshTable(flag: String = "1") = {
    dbUtil.executeUpdate("update sm_params_refresh_control set refresh_flag = " + flag + " where sm_host='" + smName + "'")
    var i = 0
    while (getRefreshFlag != "0") {
      Thread.sleep(1000)
      i = i + 1
      logger.debug("wait for sm refresh data " + i + "s")
    }
  }
}